<?php

namespace backend\controllers;

use common\models\memuser\Memuser;
use common\models\user\User;
use Yii;
use common\models\member\Member;
use common\models\member\MemberSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use zhongkefu\zhongkefu;
use zhongkefu\helpers\Utils;
use common\models\adminlog\AdminLog;
use zhongkefu\helpers\Excelwriter;
/**
 * MemberController implements the CRUD actions for Member model.
 */
class MemberController extends BackendController
{
    
    public function actions()
    {
    return [
            'upload' => [
                'class' => 'kucha\ueditor\UEditorAction',
                'config' => [
                    "imageUrlPrefix"  => Yii::$app->params['ueditor'],//图片访问路径前缀
                    "imagePathFormat" => '/upload/ariticle/ueditor/{yyyy}{mm}{dd}/{time}{rand:6}',//上传保存路径
                    "imageRoot" => Yii::getAlias("@webroot"),
                ],
            ]
        ];
    }

    /**
     * Lists all Member models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new MemberSearch();
        if(Yii::$app->user->identity->getId()==1) {
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        }else{
            $dataProvider = $searchModel->memsearch(Yii::$app->request->queryParams,Yii::$app->user->identity->getId());
        }
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Member model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
		$model = $this->findModel($id);
		Adminlog::addlog(yii::$app->user->id, "查看会员 ".$model->username);
        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new Member model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Member();

             //上传图片插件
        if ($model->load(Yii::$app->request->post()) ) {
           
            $model->faceimg = UploadedFile::getInstance($model, 'faceimg');
            if(isset(Yii::$app->request->post()['tag'])){
                $model->optiontag = json_encode(Yii::$app->request->post()['tag']);
            }
           
            if($model->faceimg){
                $siteRoot = Yii::$app->params['memberimg'];
                $json = Utils::uploadfile($_FILES['Member']['tmp_name']['faceimg'],$_FILES['Member']['name']['faceimg'],$siteRoot);
                $model->faceimg = $json;
            }

            $model->loc_province = Yii::$app->request->post()['loc_province'];
            $model->loc_city = Yii::$app->request->post()['loc_city'];
            $model->loc_town = Yii::$app->request->post()['loc_town'];
            $model->setPassword(Yii::$app->request->post()['Member']['password']);
            $model->generateAuthKey();

            if($model->save()){
				$name = Yii::$app->request->post()['Member']['username'];
				Adminlog::addlog(yii::$app->user->id, "添加会员 ".$name);
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                
                Yii::$app->session->setFlash('warning', Yii::t('app', '图片不能为空'));
                return $this->render('create', [
                    'model' => $model,
                ]);
            }

        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
	
	public function actionImport()
	{
		$province=array();
		$minfo = member::findBySql("select ip from member where status=20")->asArray()->all();
		
		$excel = new ExcelWriter('utf8', '会员统计数据'.date("Y-m-d",time()));
        if (!$minfo) {
            echo "无数据";
            return;
        }

        $cols = array();
        $cols_item = array();
        $cols_item[] = '省份';
        $cols_item[] = '注册人数';

        $cols[] = $cols_item;
        if(is_array($minfo) && count($minfo) > 0) {
			
			foreach($minfo as $k => $v){
				$info = $this->GetIpLookup($v['ip']);
				$province[] = $info['province'];
			} 
			
			$areaval = array_count_values($province);
			foreach($areaval as $key => $val){
				$tmp_col = array();
				$tmp_col[] = $key;		
				$tmp_col[] = $val."人";
				$cols[] = $tmp_col;
			}

        }
        $excel->add_array($cols);
        $excel->output();
		die;
	}

    /**
     * Updates an existing Member model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) ) {
            $model->faceimg = UploadedFile::getInstance($model, 'faceimg');
            if($model->faceimg){
                $siteRoot = Yii::$app->params['memberimg'];
                $json = Utils::uploadfile($_FILES['Member']['tmp_name']['faceimg'],$_FILES['Member']['name']['faceimg'],$siteRoot);
                $model->faceimg = $json;
            }
            //若为更新图片，则为原数据库中图片名称
            if (!$model->faceimg) {
                $new = $this->findModel($id);
                $model->faceimg = $new->faceimg;
            }

            $model->yyzhizhaoimg = UploadedFile::getInstance($model, 'yyzhizhaoimg');
            if($model->yyzhizhaoimg){
                $siteRoot = Yii::$app->params['memberimg'];
                $json = Utils::uploadfile($_FILES['Member']['tmp_name']['yyzhizhaoimg'],$_FILES['Member']['name']['yyzhizhaoimg'],$siteRoot);
                $model->yyzhizhaoimg = $json;
            }
            //若为更新图片，则为原数据库中图片名称
            if (!$model->yyzhizhaoimg) {
                $new = $this->findModel($id);
                $model->yyzhizhaoimg = $new->yyzhizhaoimg;
            }

            $model->cardz = UploadedFile::getInstance($model, 'cardz');
            if($model->cardz){
                $siteRoot = Yii::$app->params['memberimg'];
                $json = Utils::uploadfile($_FILES['Member']['tmp_name']['cardz'],$_FILES['Member']['name']['cardz'],$siteRoot);
                $model->cardz = $json;
            }
            //若为更新图片，则为原数据库中图片名称
            if (!$model->cardz) {
                $new = $this->findModel($id);
                $model->cardz = $new->cardz;
            }

            $model->cardf = UploadedFile::getInstance($model, 'cardf');
            if($model->cardf){
                $siteRoot = Yii::$app->params['memberimg'];
                $json = Utils::uploadfile($_FILES['Member']['tmp_name']['cardf'],$_FILES['Member']['name']['cardf'],$siteRoot);
                $model->cardf = $json;
            }
            //若为更新图片，则为原数据库中图片名称
            if (!$model->cardf) {
                $new = $this->findModel($id);
                $model->cardf = $new->cardf;
            }

            $model->fwdengjiimg = UploadedFile::getInstance($model, 'fwdengjiimg');
            if($model->fwdengjiimg){
                $siteRoot = Yii::$app->params['memberimg'];
                $json = Utils::uploadfile($_FILES['Member']['tmp_name']['fwdengjiimg'],$_FILES['Member']['name']['fwdengjiimg'],$siteRoot);
                $model->fwdengjiimg = $json;
            }
            //若为更新图片，则为原数据库中图片名称
            if (!$model->fwdengjiimg) {
                $new = $this->findModel($id);
                $model->fwdengjiimg = $new->fwdengjiimg;
            }

            if(isset(Yii::$app->request->post()['tag'])){
                $model->optiontag = json_encode(Yii::$app->request->post()['tag']);
            }
            if(!empty(Yii::$app->request->post()['Member']['password'])){
                $model->setPassword(Yii::$app->request->post()['Member']['password']);
                $model->generateAuthKey();
            }
            if(isset(Yii::$app->request->post()['Member']['company'])){
                $model->company = Yii::$app->request->post()['Member']['company'];
            }

            if(!empty(Yii::$app->request->post()['loc_province'])){
                $model->loc_province = Yii::$app->request->post()['loc_province'];
            }
            if(!empty(Yii::$app->request->post()['loc_city'])){
                $model->loc_city = Yii::$app->request->post()['loc_city'];
            }
            if(!empty(Yii::$app->request->post()['loc_town'])){
                $model->loc_town = Yii::$app->request->post()['loc_town'];
            }
            if(isset(Yii::$app->request->post()['Member']['address'])){
                $model->address = Yii::$app->request->post()['Member']['address'];
            }
            if(isset(Yii::$app->request->post()['Member']['farentel'])){
                $model->farentel = Yii::$app->request->post()['Member']['farentel'];
            }
            if(isset(Yii::$app->request->post()['Member']['grnum'])){
                $model->grnum = Yii::$app->request->post()['Member']['grnum'];
            }
            if(isset(Yii::$app->request->post()['Member']['zhucezj'])){
                $model->zhucezj = Yii::$app->request->post()['Member']['zhucezj'];
            }
            if(isset(Yii::$app->request->post()['Member']['faren'])){
                $model->faren = Yii::$app->request->post()['Member']['faren'];
            }
            if(isset(Yii::$app->request->post()['Member']['farenphone'])){
                $model->farenphone = Yii::$app->request->post()['Member']['farenphone'];
            }
            if(isset(Yii::$app->request->post()['Member']['farenemail'])){
                $model->farenemail = Yii::$app->request->post()['Member']['farenemail'];
            }
             if(isset(Yii::$app->request->post()['Member']['grnum'])){
                $model->grnum = Yii::$app->request->post()['Member']['grnum'];
            }
            if(isset(Yii::$app->request->post()['Member']['zhucezj'])){
                $model->zhucezj = Yii::$app->request->post()['Member']['zhucezj'];
            }
            if(isset(Yii::$app->request->post()['Member']['yyzhizao'])){
                $model->yyzhizao = Yii::$app->request->post()['Member']['yyzhizao'];
            }
            if(isset(Yii::$app->request->post()['Member']['zcdizhi'])){
                $model->zcdizhi = Yii::$app->request->post()['Member']['zcdizhi'];
            }
            if(isset(Yii::$app->request->post()['Member']['qychengliqychengli'])){
                $model->qychengli = Yii::$app->request->post()['Member']['qychengli'];
            }
            if(isset(Yii::$app->request->post()['Member']['qychenglizhi'])){
                $model->qychenglizhi = Yii::$app->request->post()['Member']['qychenglizhi'];
            }
             if(isset(Yii::$app->request->post()['Member']['jyfanwei'])){
                $model->jyfanwei = Yii::$app->request->post()['Member']['jyfanwei'];
            }
            if(isset(Yii::$app->request->post()['Member']['card'])){
                $model->card = Yii::$app->request->post()['Member']['card'];
            }
            if($model->save()){
				$name = Yii::$app->request->post()['Member']['username'];
				Adminlog::addlog(yii::$app->user->id, "修改会员 ".$name);
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                return $this->render('update', [
                    'model' => $model,
                ]);
            }

        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Member model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
		$model->delete();
		Adminlog::addlog(yii::$app->user->id, '删除会员 '.$model->username);
        return $this->redirect(['index']);
    }


    public function actionUncheck(){
        $searchModel = new MemberSearch();
        $dataProvider = $searchModel->unchecksearch(Yii::$app->request->queryParams);

        return $this->render('uncheck', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionCheck(){
        $searchModel = new MemberSearch();
        $dataProvider = $searchModel->checksearch(Yii::$app->request->queryParams);

        return $this->render('check', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionWaitcheck(){
        $searchModel = new MemberSearch();
        $dataProvider = $searchModel->waitchecksearch(Yii::$app->request->queryParams);

        return $this->render('waitcheck', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * 启用按钮
     * If update is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionStart()
    {
        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $ids = explode(',',$ids);
            foreach($ids as $id){
                $model = Member::findOne(['id' => $id]);
                Member::updateAll(['status'=>Member::STATUS_SUCCESS],['id' =>$model->id]);
            }
            return true;
        }
    }

    /**
     * 停用按钮
     * If update is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionStop()
    {

        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $reason = zhongkefu::$app->request->post()["reason"];
            $ids = explode(',',$ids);
            foreach($ids as $id){

                $model = Member::findOne(['id' => $id]);
                Member::updateAll(['status'=>Member::STATUS_DELETED,'reason'=>$reason],['id' =>$model->id]);
            }
            return true;
        }
    }
    /**
     * 删除按钮
     * If update is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionAlldelete()
    {
		$artname="";
        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $ids = explode(',',$ids);

			foreach($ids as $val){
				$models = Member::findOne(['id' => $val]);
				$artname .= $models->username.",";
			}
			$artname = substr($artname,0,-1);
			
            foreach($ids as $id){
                $model = Member::findOne(['id' => $id]);
                $this->findModel($id)->delete();
            }

			Adminlog::addlog(yii::$app->user->id, '批量删除会员 '.$artname);
            return true;
        }
    }

    /**
     * Finds the Member model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Member the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Member::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
	
	function GetIpLookup($ip = ''){
		if(empty($ip)){
			return 'unkonw'; 
		}
		$res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);  
		if(empty($res)){ return false; }
		$jsonMatches = array();
		preg_match('#\{.+?\}#', $res, $jsonMatches);
		if(!isset($jsonMatches[0])){ return false; }
		$json = json_decode($jsonMatches[0], true);
		if(isset($json['ret']) && $json['ret'] == 1){
			$json['ip'] = $ip;
			unset($json['ret']);
		}else{
			return false;  
		}
		return $json;  
	}
	public function actionUserlist(){
        if(isset(zhongkefu::$app->request->post()["id"])){
            $id = zhongkefu::$app->request->post()["id"];
            $member = Member::find()->select('id,uid')->andWhere(['id'=>$id])->asArray()->one();
            $user = User::find()->with('group')->asArray()->all();
            $arr = [
                'user'=>$user,
                'mid'=>$id,
                'uid'=>$member['uid']
            ];
            return json_encode($arr);
        }
    }
    public function actionChangelist(){
        $user = User::find()->with('group')->asArray()->all();
        $arr = [
            'user'=>$user,
        ];
        return json_encode($arr);
    }
    public function actionChangeuser(){

            $id = zhongkefu::$app->request->post()["memberid"];
            $uid = zhongkefu::$app->request->post()["id"];
            Member::updateAll(['uid'=>$uid],['id' =>$id]);
            return true;

    }
    public function actionChangeseluser(){
        $id = zhongkefu::$app->request->post()["memberid"];
        $uid = zhongkefu::$app->request->post()["userid"];

        foreach ($uid as $val){
            $mems = explode(',',$id);

            foreach ($mems as $mem){
                $isset = Memuser::find()->andWhere(['mid'=>$mem])->andWhere(['uid'=>$val])->all();
                if(!$isset){
                    $memuser = new Memuser();
                    $memuser->mid = $mem;
                    $memuser->uid = $val;
                    $memuser->shareid  = \Yii::$app->user->identity->getId();
                    $memuser->save();
                }
            }
        }
        return true;
    }
    /**
     * Lists all Member models.
     * @return mixed
     */
    public function actionShareme()
    {
        $searchModel = new MemberSearch();
        $dataProvider = $searchModel->mesearch(Yii::$app->request->queryParams,Yii::$app->user->identity->getId());

        return $this->render('shareme', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Lists all Member models.
     * @return mixed
     */
    public function actionSharehei()
    {
        $searchModel = new MemberSearch();
        $dataProvider = $searchModel->heisearch(Yii::$app->request->queryParams,Yii::$app->user->identity->getId());

        return $this->render('sharehei', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
}
